package intranet.client;

import java.util.HashMap;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.PushButton;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * @author Robin TROADEC
 *
 */
public class AdminSubject extends HorizontalPanel
{
	
	protected VerticalPanel centerPanel,subjectListPan,subjectInfoPan,subjectDialog;
	protected FlowPanel subjectInfoName;
	protected Grid subjectInfoHour,subjectInfoHourDialog;
	protected HorizontalPanel  subjectSubjectPan;
	protected ListBox subjectList;
	protected PushButton subjectAdd,subjectRem,subjectValid;
	protected ValidTextBox subjectName,subjectAddTitle,subjectCode,subjectAddCode;
	protected DialogBox subjectAddDialog;
	protected Button subjectValidAdd,subjectCancel;
	protected HorizontalPanel subjectLabel,subjectButton;
	protected ValidIntegerTextBox hourCM,hourTP,hourTD,grpCM,grpTD,grpTP;
	protected ValidIntegerTextBox hourCMDialog,hourTPDialog,hourTDDialog,grpCMDialog,grpTDDialog,grpTPDialog;
	private static final String SERVER_ERROR = "An error occurred while "
		+ "attempting to contact the server. Please check your network "
		+ "connection and try again.";

	
	private final DataBaseServiceAsync dataService = GWT
	.create(DataBaseService.class);
	private final TemplatesTabFuncAsync templatesFunc = GWT
	.create(TemplatesTabFunc.class);
	
	


/**
 * Creation d'un panel d'administration des matières
 * @param La session courante
 */
	public AdminSubject(Session s)
	{
		subjectListPan = new VerticalPanel();
		subjectListPan.setHorizontalAlignment(ALIGN_CENTER);
		
		subjectButton = new HorizontalPanel();
		

		//Panel de boutton ajout/suppr subject
		subjectAdd = new PushButton(new Image("add.png"));
		subjectAdd.setSize("20px", "20px");
		subjectAdd.addClickHandler(new ClickHandler()
		{
			public void onClick(ClickEvent event)
			{
				//Préparation Dialog
				subjectAddDialog = new DialogBox();
				
				
				subjectAddDialog.setGlassEnabled(true);
				subjectAddDialog.setAnimationEnabled(true);
				subjectAddDialog.setPopupPosition(500, 100);
				subjectDialog = new VerticalPanel();
				subjectDialog.setHorizontalAlignment(ALIGN_CENTER);
				
				subjectValidAdd = new Button("Ajouter");
				//ajout de l'event sur le bouton ajouter
				subjectValidAdd.addClickHandler(new ClickHandler()
				{
					public void onClick(ClickEvent event)
					{
						//colorisation des champs défaillants
						if (hourCMDialog.getText().equals(""))
							hourCMDialog.addStyleName("error");
						else
							hourCMDialog.removeStyleName("error");
						
						if (hourTDDialog.getText().equals(""))
							hourTDDialog.addStyleName("error");
						else
							hourTDDialog.removeStyleName("error");
						
						if (hourTPDialog.getText().equals(""))
							hourTPDialog.addStyleName("error");
						else
							hourTPDialog.removeStyleName("error");
						
						if (grpCMDialog.getText().equals(""))
							grpCMDialog.addStyleName("error");
						else
							grpCMDialog.removeStyleName("error");
						
						if (grpTDDialog.getText().equals(""))
							grpTDDialog.addStyleName("error");
						else
							grpTDDialog.removeStyleName("error");
						
						if (grpTPDialog.getText().equals(""))
							grpTPDialog.addStyleName("error");
						else
							grpTPDialog.removeStyleName("error");
						
						if (subjectAddCode.getText().equals(""))
							subjectAddCode.addStyleName("error");
						else
							subjectAddCode.removeStyleName("error");
						
						if (subjectAddTitle.getText().equals(""))
							subjectAddTitle.addStyleName("error");
						else
							subjectAddTitle.removeStyleName("error");
						
						if (isDialogValid())
						{
							
							String r = "insert into subject (subject_name,subject_code,subject_cm,subject_group_cm,subject_tp,subject_group_tp,subject_td,subject_group_td) values('"+subjectAddTitle.getText()+"','"+subjectAddCode.getText()+"','"+hourCMDialog.getText()+"','"+grpCMDialog.getText()+"','"+hourTPDialog.getText()+"','"+grpTPDialog.getText()+"','"+hourTDDialog.getText()+"','"+grpTDDialog.getText()+"')";
							dataService.insert(r, new AsyncCallback<Integer>()
							{
								public void onFailure(Throwable caught)
								{}

								public void onSuccess(Integer result)
								{
									subjectAddDialog.hide();
									subjectAddCode.removeStyleName("error");
									subjectAddTitle.removeStyleName("error");
									initListe();
								}
							});
						}
					}
				});
					
					//Ajout de l'event sur le bouton annuler
				subjectCancel = new Button("Annuler");
					subjectCancel.addClickHandler( new ClickHandler()
					{
						
						public void onClick(ClickEvent event)
						{
							subjectAddDialog.hide();						
						}
					});
					
					
					//Formatage CSS du panel
				subjectAddTitle = new ValidTextBox();
				subjectAddCode = new ValidTextBox();
				
				subjectDialog.add(new HTML("Nom de la filière"));
				subjectDialog.add(subjectAddTitle);
				subjectDialog.add(new HTML("Code de la filière"));
				subjectDialog.add(subjectAddCode);
				
				subjectInfoHourDialog = new Grid(3,4);
				
				subjectInfoHourDialog.setHTML(0, 1, "<b>CM</b>");
				subjectInfoHourDialog.getCellFormatter().setHorizontalAlignment(0,1, ALIGN_CENTER);
				subjectInfoHourDialog.setHTML(0, 2, "<b>TD</b>");
				subjectInfoHourDialog.getCellFormatter().setHorizontalAlignment(0,2, ALIGN_CENTER);
				subjectInfoHourDialog.setHTML(0, 3, "<b>TP</b>");
				subjectInfoHourDialog.getCellFormatter().setHorizontalAlignment(0,3, ALIGN_CENTER);
				subjectInfoHourDialog.setHTML(1, 0, "<b>Nombre d'heures</b>");
				subjectInfoHourDialog.getCellFormatter().setHorizontalAlignment(1,0, ALIGN_CENTER);
				subjectInfoHourDialog.setHTML(2, 0, "<b>Nombre de groupes</b>");
				subjectInfoHourDialog.getCellFormatter().setHorizontalAlignment(2,0, ALIGN_CENTER);
				
				hourCMDialog = new ValidIntegerTextBox();
				hourCMDialog.setWidth("30px");
				subjectInfoHourDialog.setWidget(1,1, hourCMDialog);
				
				hourTDDialog = new ValidIntegerTextBox();
				hourTDDialog.setWidth("30px");
				subjectInfoHourDialog.setWidget(1,2, hourTDDialog);
				
				hourTPDialog = new ValidIntegerTextBox();
				hourTPDialog.setWidth("30px");
				subjectInfoHourDialog.setWidget(1,3, hourTPDialog);
				
				grpCMDialog = new ValidIntegerTextBox();
				grpCMDialog.setWidth("30px");
				subjectInfoHourDialog.setWidget(2,1, grpCMDialog);;
				
				grpTDDialog = new ValidIntegerTextBox();
				grpTDDialog.setWidth("30px");
				subjectInfoHourDialog.setWidget(2,2, grpTDDialog);
				
				grpTPDialog = new ValidIntegerTextBox();
				grpTPDialog.setWidth("30px");
				subjectInfoHourDialog.setWidget(2,3, grpTPDialog);
				
				subjectDialog.add(subjectInfoHourDialog);
				
				subjectDialog.add(subjectValidAdd);
				subjectDialog.add(subjectCancel);
				subjectAddDialog.add(subjectDialog);
				
				subjectAddDialog.show();				
			}
		});
		subjectRem = new PushButton(new Image("delete.png"));
		subjectRem.setSize("20px", "20px");
		//Ajout de l'event sur le bouton de suppression
		subjectRem.addClickHandler(new ClickHandler()
		{
			public void onClick(ClickEvent event)
			{
				if (Window.confirm("Êtes-vous sûr de vouloir supprimer cette matière? Toutes les données concernant cette matière seront perdues" ))
				{
					if (subjectList.getSelectedIndex()>=0)
					{	
						String r="delete from subject_course where subject_id='"+subjectList.getValue(subjectList.getSelectedIndex())+"'";
						
						dataService.delete(r,new AsyncCallback<Integer>()
						{
							public void onSuccess(Integer result)
							{		
								String r="select * from document where document_subject='"+subjectList.getValue(subjectList.getSelectedIndex())+"'";
								dataService.select(r, new AsyncCallback<HashMap<String,String[]>>()
								{
									public void onFailure(Throwable caught)
									{}

									public void onSuccess(HashMap<String, String[]> result)
									{
										
											for (int i = 0;i<result.get("document_id").length;i++)
											{											
												templatesFunc.deletePdf(result.get("document_path")[i], new AsyncCallback<Boolean>()
												{
													public void onFailure(Throwable caught)
													{}
	
													public void onSuccess(Boolean result)
													{}
												});								
											}
											
										String r = "delete from document where document_subject='"+subjectList.getValue(subjectList.getSelectedIndex())+"'";
										dataService.delete(r, new AsyncCallback<Integer>()
										{
											public void onFailure(Throwable caught)
											{}
	
											public void onSuccess(Integer result)
											{
												String r="delete from subject where subject_id='"+subjectList.getValue(subjectList.getSelectedIndex())+"'";
												dataService.delete(r, new AsyncCallback<Integer>()
												{
													public void onFailure(Throwable caught)
													{}
													public void onSuccess(Integer result)
													{
														subjectList.removeItem(subjectList.getSelectedIndex());
														initListe();
													}
												});
											}
										});	
									}//fin onsuccess
								});//fin select * from document
									
							}//fin onsucess
							
							public void onFailure(Throwable caught)
							{}
						});	
					}//fin if selected
				}//fin if window confirm
			}
		});
		subjectButton.add(subjectAdd);
		subjectButton.add(subjectRem);	

		
		subjectList = new ListBox();
		subjectList.setSize(Window.getClientWidth()*16/20*1/4+"px", Window.getClientHeight()*9/10*3/4+"px");
		//Ajout de l'vent de mise a jour des infos sur le changement d'item de la liste
		subjectList.addChangeHandler(new ChangeHandler()
		{
			public void onChange(ChangeEvent event)
			{
				updatesubjectInfo(subjectList.getValue(subjectList.getSelectedIndex()));		
			}
		});
		
		//initialisation de l'ensemble des matières
 		initListe();


		//Panel liste les matiere
		subjectListPan.add(subjectList);
		subjectListPan.add(subjectButton);

		//Panel des infos
		subjectInfoPan = new VerticalPanel();
		subjectInfoPan.setSize(Window.getClientWidth()*16/20*2/3+"px", Window.getClientHeight()*9/10*4/5+"px");
		subjectInfoPan.setHorizontalAlignment(ALIGN_CENTER);
		HTML genInfo = new HTML("Informations générales");
		genInfo.addStyleName("backBlue");
		subjectInfoPan.add (genInfo);

		subjectInfoName = new FlowPanel();
		subjectInfoName.add(new HTML("<b>Nom</b>"));
	
		subjectName = new ValidTextBox();
		subjectInfoName.add(subjectName);
		subjectName.setWidth(Window.getClientWidth()*16/20*1/8+"px");
		subjectInfoName.add(new HTML("<b>Code</b>"));
		subjectCode = new ValidTextBox();
		subjectCode.setWidth(Window.getClientWidth()*16/20*1/8+"px");
		subjectInfoName.add(subjectCode);

		
		subjectInfoPan.add(subjectInfoName);
		HTML hourInfo = new HTML("Informations horaires");
		hourInfo.addStyleName("backBlue");
		subjectInfoPan.add (hourInfo);

		subjectInfoHour = new Grid(3,4);
		
		subjectInfoHour.setHTML(0, 1, "<b>CM</b>");
		subjectInfoHour.getCellFormatter().setHorizontalAlignment(0,1, ALIGN_CENTER);
		subjectInfoHour.setHTML(0, 2, "<b>TD</b>");
		subjectInfoHour.getCellFormatter().setHorizontalAlignment(0,2, ALIGN_CENTER);
		subjectInfoHour.setHTML(0, 3, "<b>TP</b>");
		subjectInfoHour.getCellFormatter().setHorizontalAlignment(0,3, ALIGN_CENTER);
		subjectInfoHour.setHTML(1, 0, "<b>Nombre d'heures</b>");
		subjectInfoHour.getCellFormatter().setHorizontalAlignment(1,0, ALIGN_CENTER);
		subjectInfoHour.setHTML(2, 0, "<b>Nombre de groupes</b>");
		subjectInfoHour.getCellFormatter().setHorizontalAlignment(2,0, ALIGN_CENTER);
		
		hourCM = new ValidIntegerTextBox();
			hourCM.setWidth(Window.getClientWidth()*16/20*1/8+"px");
		subjectInfoHour.setWidget(1,1, hourCM);
		hourTD = new ValidIntegerTextBox();
		hourTD.setWidth(Window.getClientWidth()*16/20*1/8+"px");
		subjectInfoHour.setWidget(1,2, hourTD);
		hourTP = new ValidIntegerTextBox();
		hourTP.setWidth(Window.getClientWidth()*16/20*1/8+"px");
		subjectInfoHour.setWidget(1,3, hourTP);
		grpCM = new ValidIntegerTextBox();
		grpCM.setWidth(Window.getClientWidth()*16/20*1/8+"px");
		subjectInfoHour.setWidget(2,1, grpCM);;
		grpTD = new ValidIntegerTextBox();
		grpTD.setWidth(Window.getClientWidth()*16/20*1/8+"px");
		subjectInfoHour.setWidget(2,2, grpTD);
		grpTP = new ValidIntegerTextBox();
		grpTP.setWidth(Window.getClientWidth()*16/20*1/8+"px");
		subjectInfoHour.setWidget(2,3, grpTP);
		
		

		subjectInfoPan.add(subjectInfoHour);
		subjectValid = new PushButton("Valider");
			subjectValid.setSize("50px", "20px");
		//Ajout de l'event sur le bouton valider de la popup
		subjectValid.addClickHandler(new ClickHandler()
		{
			public void onClick(ClickEvent event)
			{
				//Mise en valeur des champs défaillants
				if (hourCM.getText().equals(""))
					hourCM.addStyleName("error");
				else
					hourCM.removeStyleName("error");
				
				if (hourTD.getText().equals(""))
					hourTD.addStyleName("error");
				else
					hourTD.removeStyleName("error");
				
				if (hourTP.getText().equals(""))
					hourTP.addStyleName("error");
				else
					hourTP.removeStyleName("error");
				
				if (grpCM.getText().equals(""))
					grpCM.addStyleName("error");
				else
					grpCM.removeStyleName("error");
				
				if (grpTD.getText().equals(""))
					grpTD.addStyleName("error");
				else
					grpTD.removeStyleName("error");
				
				if (grpTP.getText().equals(""))
					grpTP.addStyleName("error");
				else
					grpTP.removeStyleName("error");
				
				if (subjectCode.getText().equals(""))
					subjectCode.addStyleName("error");
				else
					subjectCode.removeStyleName("error");
				
				if (subjectName.getText().equals(""))
					subjectName.addStyleName("error");
				else
					subjectName.removeStyleName("error");
				
				if (allIsValid())
				{
					String r = "update subject set subject_name='"+subjectName.getText()+"',subject_cm='"+hourCM.getText()+"',subject_group_cm='"+grpCM.getText()+"',subject_td='"+hourTD.getText()+"',subject_group_td='"+grpTD.getText()+"',subject_tp='"+hourTP.getText()+"',subject_group_tp='"+grpTP.getText()+"',subject_code='"+subjectCode.getText()+"' where subject_id='"+subjectList.getValue(subjectList.getSelectedIndex())+"'";
					dataService.update(r, new AsyncCallback<Integer>()
					{
						public void onFailure(Throwable caught)
						{}

						public void onSuccess(Integer result)
						{
								Window.alert("Sauvegarde réussie");						
						}
					});
				}	
			}
		});
		validEnabled(false);
		subjectInfoPan.add(subjectValid);
		
		
		//Ajout au panel général
		this.setHorizontalAlignment(ALIGN_CENTER);
		this.add(subjectListPan);	
		this.add(subjectInfoPan);
		
	}

	/**
	 * Fonction qui récupere et affiche les informations sur la matière séléctionnée
	 * @param id de la matière
	 */
	public void updatesubjectInfo(final String id )
	{
		validEnabled(true);
		
		String r = "select * from subject where subject_id='"+subjectList.getValue(subjectList.getSelectedIndex())+"'";
		dataService.select(r, new AsyncCallback<HashMap<String,String[]>>()
		{
			public void onFailure(Throwable caught)
			{}
			public void onSuccess(HashMap<String, String[]> result)
			{
				hourCM.setText(result.get("subject_cm")[0]);
				hourTD.setText(result.get("subject_td")[0]);
				hourTP.setText(result.get("subject_tp")[0]);
				grpCM.setText(result.get("subject_group_cm")[0]);
				grpTD.setText(result.get("subject_group_td")[0]);
				grpTP.setText(result.get("subject_group_tp")[0]);	
				
				subjectCode.setText(result.get("subject_code")[0]);
				subjectName.setText(result.get("subject_name")[0]);
			}
		});
	}
	
	/**
	 * Initialisation de la liste des matières
	 */
	public void initListe()
	{
		
		subjectList.clear();
		subjectList.setVisibleItemCount(10);
		subjectList.setSize(Window.getClientWidth()*16/20*1/4+"px", Window.getClientHeight()*9/10*2/3+"px");
		
		String r="select * from subject ";
		dataService.select(r, new AsyncCallback<HashMap<String,String[]>>()
		{
			public void onSuccess(HashMap<String, String[]> result)
			{
				for (int i=0;i<result.get("subject_id").length;i++)
				{
					subjectList.addItem(result.get("subject_name")[i],result.get("subject_id")[i]);
				}
			}
			
			public void onFailure(Throwable caught)
			{
				Window.alert("Select error : "+SERVER_ERROR);				
			}
		});
		
		
	}
	
	/**
	 * Fonction de redimensionnement
	 */
	public void onResize()
	{
		subjectList.setSize(Window.getClientWidth()*16/20*1/4+"px", Window.getClientHeight()*9/10*3/4+"px");
		subjectInfoPan.setSize(Window.getClientWidth()*16/20*(2/3+1/25)+"px", Window.getClientHeight()*9/10*4/5+"px");
		hourCM.setWidth(Window.getClientWidth()*16/20*1/8+"px");
		hourTD.setWidth(Window.getClientWidth()*16/20*1/8+"px");
		hourTP.setWidth(Window.getClientWidth()*16/20*1/8+"px");
		grpCM.setWidth(Window.getClientWidth()*16/20*1/8+"px");
		grpTD.setWidth(Window.getClientWidth()*16/20*1/8+"px");
		grpTP.setWidth(Window.getClientWidth()*16/20*1/8+"px");
		subjectCode.setWidth(Window.getClientWidth()*16/20*1/8+"px");
		subjectInfoName.setWidth(Window.getClientWidth()*16/20*1/8+"px");
	}
	
	/**
	 * Fonction d'activation/desactivation des champs
	 * @param boolean
	 */
	public void validEnabled(boolean b)
	{
		hourCM.setEnabled(b);
		hourTD.setEnabled(b);
		hourTP.setEnabled(b);
		grpCM.setEnabled(b);
		grpTD.setEnabled(b);
		grpTP.setEnabled(b);
		
		subjectCode.setEnabled(b);
		subjectName.setEnabled(b);
		subjectValid.setEnabled(b);
	}
	
	/**
	 * Fonction de vérification de la validité de tout les champs
	 * @return boolean
	 */
	public Boolean allIsValid()
	{
		if (hourCM.getText().equals(""))
			return false;	
		if (hourTD.getText().equals(""))
			return false;	
		if (hourTP.getText().equals(""))
			return false;	
		if (grpCM.getText().equals(""))
			return false;	
		if (grpTD.getText().equals(""))
			return false;		
		if (grpTP.getText().equals(""))
			return false;	
		if (subjectCode.getText().equals(""))
			return false;	
		if (subjectName.getText().equals(""))
			return false;
		
		return true;
	}
	
	/**
	 * Fonction de vérification de la validité de tout les champs de la boite de dialog
	 * @return boolean
	 */
	public Boolean isDialogValid()
	{
		if (hourCMDialog.getText().equals(""))
			return false;	
		if (hourTDDialog.getText().equals(""))
			return false;	
		if (hourTPDialog.getText().equals(""))
			return false;	
		if (grpCMDialog.getText().equals(""))
			return false;	
		if (grpTDDialog.getText().equals(""))
			return false;		
		if (grpTPDialog.getText().equals(""))
			return false;	
		if (subjectAddCode.getText().equals(""))
			return false;	
		if (subjectAddTitle.getText().equals(""))
			return false;
		
		return true;
	}
}
